package com.example.serviceapp;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.serviceapp.services.MyForegroundService;
import com.example.serviceapp.services.MyService;

import androidx.appcompat.app.AppCompatActivity;

public class ForegroundServiceActivity extends AppCompatActivity implements View.OnClickListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button startService = (Button) findViewById(R.id.start_service);
        Button stopService = (Button) findViewById(R.id.stop_service);
        startService.setOnClickListener(this);
        stopService.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_service:
                Intent startIntent = new Intent(this, MyForegroundService.class);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    //android8.0以上通过startForegroundService启动service
                    startForegroundService(startIntent);
                } else {
                    startService(startIntent);
                }
                break;
            case R.id.stop_service:
                Intent stopIntent = new Intent(this, MyForegroundService.class);
                stopService(stopIntent); // 停止服务
                break;
            default:
                break;
        }
    }
}